<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{

        $user = User::model()->findByAttributes(array('user_id'=>$this->username, 'status'=>'ACTIVE'));
        if($user === null){
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        }else{

            if(!CPasswordHelper::verifyPassword($this->password,$user->password))
                $this->errorCode=self::ERROR_UNKNOWN_IDENTITY;
            else{

                $row = Yii::app()->db->createCommand(array(
                    'select' => 'FN_ZZ_MULTI_NAME(A.USER_NAME,A.USER_ENG_NAME,:LANG_CODE) AS USER_NAME, A.FORMAT_DATE, A.FORMAT_TIME, A.LANGUAGE, C.URL',
                    'from' => 'TBL_USERS A',
                    'where' => 'USER_ID = :USER_ID',
                    'params' => array(':USER_ID'=>$this->username, ':LANG_CODE' => Yii::app()->language),
                ))->leftJoin("TBL_FILE_ATTACH_GRP B","A.AVATAR = B.FILE_ATTACH_NO")
                   ->leftJoin("TBL_FILE_ATTACH C","B.FILE_ATTACH_NO = C.FILE_ATTACH_NO AND C.FILE_DETAIL_CODE = AVATAR")
                   -> queryRow();
                Yii::app()->session['userInfo'] = CJSON::encode($row);
                $this->errorCode=self::ERROR_NONE;
            }
        }
		return !$this->errorCode;
	}
}